// We recommend using the configureStore method of the @reduxjs/toolkit package, which replaces createStore.
import { Action, createStore } from 'redux';
// useSelector react-redux
// https://github.com/reduxjs/react-redux/blob/master/src/hooks/useSelector.ts
import { createSelector } from 'reselect';

interface Todo {
  text: string;
  completed: boolean;
}

interface StateProps {
  count: { number: number };
  todos: Todo[];
  filter: boolean;
}

let initialState: StateProps = {
  count: { number: 0 },
  todos: [
    { text: '没完成的事', completed: false },
    { text: '完成的事', completed: true },
  ],
  filter: true,
};

const reducer = (state = initialState, action: Action) => {
  switch (action.type) {
    case 'ADD':
      return { ...state, count: { number: state.count.number + 1 } };
    default:
      return state;
  }
};

// 创建仓库
let store = createStore(reducer);

export const todosSelector = (state: StateProps) => state.todos;
export const filterSelector = (state: StateProps) => state.filter;

// 实现一个缓存
export const visibleTodosSelector = createSelector(
  [todosSelector, filterSelector],
  // 状态没变 就不会发生变化
  // react-redux每个组件都要从总的状态中获取一部分的属性
  // 只要这个组件需要的属性没有更新 这个组件就不要刷新
  (todos, filter) => {
    console.log('计算visibleTodos');
    return todos.filter((item) => item.completed == filter);
  },
);

const render = () => {
  let state = store.getState();
  console.log(state);
  const state1 = visibleTodosSelector(state);
  console.log(state1);
};

// 订阅
store.subscribe(render);
render();
// 派发
store.dispatch({ type: 'ADD' });

export function myCreateSelector(selectors: any, map: any) {
  let lastValue: any; // 闭包的变量
  return function (state: any) {
    if (lastValue) return lastValue;
    let values = selectors.map((selector: any) => selector(state));
    let result = map(...values);
    lastValue = result;
    return lastValue;
  };
}
